package com.chongdong.servlet;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.chongdong.annotation.CDAutowried;
import com.chongdong.annotation.CDController;
import com.chongdong.annotation.CDRequestMapping;
import com.chongdong.annotation.CDRequestParam;
import com.chongdong.annotation.CDService;

/**
 * 手写一个springMVC框架
 * @author yanxh
 *
 */
public class CDDispatherServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	/**用于读取配置文件**/
	private Properties prop = new Properties();
	
	/**存放当前扫描包下面的所有类名**/
	private List<String> classNameList = new ArrayList<String>();
	
	/**IOC**/
	private Map<String,Object> IOC = new HashMap<String,Object>();
	
	/**mapping url和method的映射关系map**/
	private List<Handler> handlerMapping = new ArrayList<Handler>();
	
    public CDDispatherServlet() {
    	
    }
    
    @Override
    public void init(ServletConfig config) {
    	//1、加载配置文件
    	initConfig(config.getInitParameter("contextConfigLocation"));
    	
    	//2、扫描相关类
    	doScanner(prop.getProperty("basePackage"));
    	
    	//3、初始化所有相关类，加载到IOC（自定义）中
    	doInstance();
    	
    	//4、实现依赖注入
    	doAutowried();
    	
    	//5、构造一个HandlerMapping，将构造好的url和method建立关系
    	initHandlerMapping();
    	
    	//6、等待请求，调用doPost或doGet，根据匹配的url去动态地调用对应的方法
    	
    	//如果加载没问题
    	System.out.println("----------------CDSpringMVC is starting!-----------");
    }
    
    /***
     * 等待请求，调用doPost或doGet，根据匹配的url去动态地调用对应的方法
     */
    private void doDispath(HttpServletRequest request, HttpServletResponse response) throws Exception{
    	Handler handler = getHandler(request);

    	if(handler == null) {
    		//找不到对应的映射，则提示请求404
    		response.getWriter().write("request 404 not found");
    		return;
    	}

		//获取自定义方法的参数列表
		Class<?>[] paramTypes = handler.method.getParameterTypes();

		//保存所有需要自动赋值的参数
		Object[] paramValues = new Object[paramTypes.length];

		//获得request的参数列表
		Map<String,String[]> params = request.getParameterMap();
		for (Entry<String,String[]> param : params.entrySet()) {
			String value = Arrays.toString(param.getValue()).replaceAll("\\[|\\]", "").replaceAll(",\\s", ",");

			//如果找到匹配的对象，开始填充值
			if(!handler.paramIndexMapping.containsKey(param.getKey()))
				continue;
			Integer index = handler.paramIndexMapping.get(param.getKey());
			paramValues[index] = convert(paramTypes[index],value);
		}
		//设置方法中的requset和response对象
		int reqIndex = handler.paramIndexMapping.get(HttpServletRequest.class.getName());
		paramValues[reqIndex] = request;
		int repIndex = handler.paramIndexMapping.get(HttpServletResponse.class.getName());
		paramValues[repIndex] = response;
		try {

			//利用反射执行目标方法
			Method method = handler.method;
			method.invoke(handler.controller, paramValues);
		}catch(Exception e) {
			e.printStackTrace();
		}
	}

	private Object convert(Class<?> clazz, String value) {
		if(Long.class == clazz) {
			return Long.valueOf(value);
		}
		return value;
	}

	/**
     * 构造一个HandlerMapping，将构造好的url和method建立关系（最关键的步骤）
     */
    private void initHandlerMapping() {
		if(IOC.isEmpty())
			return;
		for (Entry<String,Object> entry : IOC.entrySet()) {
			//扫描所有的方法
			Class<? extends Object> clzz = entry.getValue().getClass();

			//不是controller不需要进行关系映射
			if (!clzz.isAnnotationPresent(CDController.class))
				continue;

			//类上的url
			String baseUrl = "";
			//将类上的requestMapping和方法上的requestMapping进行拼接，得到url
			if(clzz.isAnnotationPresent(CDRequestMapping.class)) {
				CDRequestMapping annotation = clzz.getAnnotation(CDRequestMapping.class);
				baseUrl = annotation.value();
			}

			Method[] methods = clzz.getMethods();
			for (Method method : methods) {
				//方法没有此注解，跳过此次循环/
				if(!method.isAnnotationPresent(CDRequestMapping.class))
					continue;

				CDRequestMapping annotation = method.getAnnotation(CDRequestMapping.class);
				//将连续的/替换成单个的/
				String regex = ("/" + baseUrl + annotation.value()).replaceAll("/+", "/");

				//得到正则
				Pattern compile = Pattern.compile(regex);

				//把url和method的关系再重新分配一次
				handlerMapping.add(new Handler(compile,entry.getValue(),method));
			}
		}
	}

	/**
     * 实现依赖注入
     */
    private void doAutowried() {
		if(IOC.isEmpty())
			return;
		/**注入就是对类中定义的一些属性进行赋值，只要加了autowried注解就注入**/
		for (Entry<String, Object> enrty : IOC.entrySet()) {
			Field[] fields = enrty.getValue().getClass().getDeclaredFields();
			for (Field field : fields) {
				/**属性没有此注解，跳过**/
				if(!field.isAnnotationPresent(CDAutowried.class))
					continue;

				CDAutowried annotation = field.getAnnotation(CDAutowried.class);
				String beanName = annotation.value().trim();
				if("".equals(beanName)) {
					//默认属性名称
					beanName = field.getType().getSimpleName();
				}

				//通过反射机制强制赋值
				field.setAccessible(true);//强制访问

				try {
					field.set(enrty.getValue(), IOC.get(beanName));
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
     * 初始化所有相关类，加载到IOC（自定义）中
     */
    private void doInstance() {
    	/**类名集合为空，直接返回*/
		if(classNameList.size()==0)
			return;

		try {
			/**遍历类名集合，进行循环初始化，放入IOC**/
			for (String className : classNameList) {

				/**利用反射得到当前类**/
				Class<?> clazz = Class.forName(className);

				if(clazz.isAnnotationPresent(CDController.class)) {
					/**当前类上加了这个注解，认为其是一个controller，可以初始化**/

					/**当前类名**/
					String beanName = clazz.getSimpleName();
					/**类名首字母小写，作为ID**/
					beanName = getName(beanName);
					/**反射初始化**/
					IOC.put(beanName, clazz.newInstance());

				}else if(clazz.isAnnotationPresent(CDService.class)) {
					/**当前类上加了这个注解，也可以初始化**/

					CDService annotation = clazz.getAnnotation(CDService.class);
					String beanName = annotation.value();
					if(!"".equals(beanName.trim())) {
						//1、如果注解中自定义名称，使用自定义
						IOC.put(beanName, clazz.newInstance());
					}else {
						//2、如果没有自定义，默认首字母小写
						/**类名首字母小写，作为ID**/
						beanName = getName(beanName);
						/**反射初始化**/
						IOC.put(beanName, clazz.newInstance());
					}

					//3、对方注入的对象是接口，采用其实现接口的全程作为beanName
					Class<?>[] interfaces = clazz.getInterfaces();
					for (Class<?> c : interfaces) {
						IOC.put(c.getSimpleName(), clazz.newInstance());
					}


				}
			}
		} catch (Exception e) {

		}
	}
    
    /**
     * 类名首字母小写
     * @param beanName
     * @return
     */
	private String getName(String beanName) {
		char[] charArray = beanName.toCharArray();
		charArray[0] += 32;
		return String.valueOf(charArray);
	}

	/***
     * 扫描相关类
     */
    private void doScanner(String packageName) {

    	/**得到包的路径**/
    	URL url = this.getClass().getClassLoader().getResource("/"+packageName.replaceAll("\\.", "/"));

    	/**得到包的文件夹**/
    	File dir = new File(url.getFile());

    	/**遍历**/
    	for (File file : dir.listFiles()) {

    		if(file.isDirectory()) {
				/**递归**/
				doScanner(packageName + "." + file.getName());
			}else {
				/**加入类名集合**/
				classNameList.add(packageName +"."+file.getName().replaceAll(".class", ""));
			}
		}
    }

	/**
     * 加载配置文件
     */
	private void initConfig(String path) {
		InputStream stream = this.getClass().getClassLoader().getResourceAsStream(path);
		try {
			prop.load(stream);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				stream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	
    	try {
			doDispath(request,response);
		} catch (Exception e) {
			response.getWriter().write("request 500 error,details is "+Arrays.toString(e.getStackTrace()));
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	/**
	 * Handler记录Controlelr中的RequestMapping和Method的映射关系
	 * @author yanxh
	 *
	 */
	private class Handler{
		protected Object controller; //保存方法对应的示例
		protected Method method;   //保存映射的方法
		protected Pattern pattern; //Spring的URL是支持正则的
		protected Map<String,Integer> paramIndexMapping; //参数顺序
		
		protected Handler(Pattern pattern,Object controller,Method method) {
			this.controller = controller;
			this.method = method;
			this.pattern = pattern;
			
			paramIndexMapping = new HashMap<String,Integer>();
			putParamIndexMapping(method);
		}

		private void putParamIndexMapping(Method method2) {
			
			//提取方法中加了注解的参数
			Annotation[][] pa = method.getParameterAnnotations();
			for (int index = 0; index < pa.length; index++) {
				for (Annotation annotation : pa[index]) {
					if(annotation instanceof CDRequestParam) {
						String paramName = ((CDRequestParam)annotation).value();
						if(!"".equals(paramName.trim()))
							paramIndexMapping.put(paramName, index);
					}
				}
			}
			
			//提取方法中的request和response参数
			Class<?>[] paramTypes = method.getParameterTypes();
			for (int index = 0; index < paramTypes.length; index++) {
				Class<?> type = paramTypes[index];
				if(type == HttpServletRequest.class || type == HttpServletResponse.class) 
					paramIndexMapping.put(type.getName(), index);
			}
		}
	}
	
	/**
	 * 根据请求的url和已有的handler进行匹配
	 * @param request
	 * @return
	 */
	private Handler getHandler(HttpServletRequest request) {
		if(handlerMapping.isEmpty())
			return null;
		
		String requestURI = request.getRequestURI();
    	String contextPath = request.getContextPath();
    	requestURI.replace(contextPath, "").replaceAll("/+", "/");
    	for (Handler handler : handlerMapping) {
    		Matcher matcher = handler.pattern.matcher(requestURI);
    		if(matcher.matches())
    			return handler;
		}
    	return null;
	}
}
